<template>
    <div class="header wrap">
      <div class="header-nav">
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          @select="handleSelect"
          text-color="#000000"
          router
        >
          <el-menu-item
            :index="item.path"
            v-for="item in menuList"
            :key="item.id"
            :class="{ active: activeIndex === item.path }"
          >
            {{ item.name }}
          </el-menu-item>
        </el-menu>
      </div>
      <div class="header-left" @click="goToHome">
        <img src="../assets/img/3.jpg" alt="" />
        <h2 style="margin-top: 2px; color: #409eff">学知网教育系统</h2>
      </div>
      <div class="header-right">
        <el-input
          v-model="keyWord"
          placeholder="输入你想学的课程"
          :suffix-icon="Search"
        />
        <el-icon v-if="!isLoggedIn">
          <UserFilled />
        </el-icon>
        <el-button text v-if="!isLoggedIn" @click="toLogin">登录</el-button>
        <span v-if="!isLoggedIn">|</span>
        <el-button text v-if="!isLoggedIn" @click="toReg">注册</el-button>
        <el-dropdown v-else>
  <span class="el-dropdown-link">
    <img :src="loginStore.userInfo.avatar || '默认头像路径'" alt="用户头像" />
    <span>{{ loginStore.userInfo.nickname || '游客' }}</span>
    <el-icon class="el-icon--right">
      <CaretBottom />
    </el-icon>
  </span>
  <template #dropdown>
    <el-dropdown-menu>
      <el-dropdown-item @click="PersonalCenter(loginStore.userInfo.id)">个人中心</el-dropdown-item>
      <el-dropdown-item @click="clickOut">退出登录</el-dropdown-item>
    </el-dropdown-menu>
  </template>
</el-dropdown>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { Search, UserFilled, CaretBottom } from "@element-plus/icons-vue";
  import { ref, watch, computed } from "vue";
  import { useRouter, useRoute } from "vue-router";
  import { useLoginStore } from "@/stores/login";
  import axios from "../assets/js/axios"
  import { jwtDecode } from "jwt-decode";
  const activeIndex = ref("/");
  const router = useRouter();
  const keyWord = ref("");
  const route = useRoute();
  const loginStore = useLoginStore()
  const getUserInfoFromToken = () => {
  const token = localStorage.getItem("userToken");
  if (token) {
    const decoded: any = jwtDecode(token); // 使用 jwt-decode 解析 token
    return {
      id: decoded.id,        // 确保从 token 中解析出用户 ID
      nickname: decoded.nickname,
      avatar: decoded.avatar || '默认头像路径', // 确保有默认值
    };
  }
  return null;
};

const savedUserInfo = getUserInfoFromToken();
if (savedUserInfo) {
  loginStore.changeUserInfo(savedUserInfo); // 更新用户信息，包括 id
}

  
  // 路由监听数据
  watch(
    () => route.path,
    (val) => {
      activeIndex.value = val;
    }
  );
  
  const menuList = ref([
    { id: 1, name: "首页", path: "/" },
    { id: 2, name: "课程", path: "/courseList" },
    { id: 3, name: "名师", path: "/teacher" },
    { id: 4, name: "文章", path: "/essayList" },
  ]);
  
  const isLoggedIn = computed(() => !!loginStore.userInfo);
  
  // 跳转菜单
  const handleSelect = (key: string) => {
    router.push(key);
  };

  // 登录、注册、注销相关功能
  const toLogin = () => {
    if (!isLoggedIn.value) {
    loginStore.changeUserInfo(null);
    router.push("/login");
  }
  };
  const toReg = () => {
    router.push("/reg");
  };
  const goToHome = () => {
    router.push("/");
  };
  //退出登录
  const clickOut = () => {
    loginStore.changeUserInfo(null);
  localStorage.removeItem("userInfo");
  localStorage.removeItem("userToken"); // 移除token
  router.push("/login");
  };
  //个人中心
  const PersonalCenter = (id: any) => {
  if (id) {
    router.push({ name: 'myUser', query: { userId: id } });
  } else {
    console.error("用户 ID 未找到");
  }
};
  </script>
  
  <style scoped lang="less">
  .header {
    height: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
  
    .header-left {
      display: flex;
      align-items: center;
  
      img {
        width: 40px;
        margin-left: -710px;
        margin-top: 15px;
        margin-right: 10px;
      }
    }
  
    .header-nav {
      width: 200px;
      flex: 1;
      padding-left: 300px;
  
      .el-menu {
        border: none;
      }
    }
  
    .header-right {
      display: flex;
      align-items: center;
  
      :deep .el-input {
        width: 300px;
        margin-right: 100px;
  
        .el-input__wrapper {
          border-radius: 25px;
        }
      }
      img {
        width: 42px;
        height: 42px;
        margin-right: 4px;
        vertical-align: middle;
      }
      
    }
  }
  </style>